import fetch from 'fermionjs/lib/fetch';
import urlPathConcat from '@kuiper-helpers/url-path-concat/dist';
import errorCodesBuilder from '../../../helpers/errorCodesBuilder';
import pkg from '../../../../../package.json';

const errorCodes = errorCodesBuilder();

export default async function initBalance({ uid, planId: pid }) {
	const {
		log,
		app: {
			model: { User, Balance },
			config: {
				[pkg.name]: { serviceApi, token },
			},
		},
	} = this;

	let balance;
	try {
		const api = urlPathConcat(serviceApi, `/api/v2/users/add`);
		await fetch(api, {
			method: 'POST',
			headers: {
				cookie: `token=${token}`,
			},
			body: JSON.stringify({ uid }),
		});
		balance = await Balance.findOne({ uid });
		await Promise.all([
			User.updateOne(
				{ _id: uid },
				{
					$set: {
						balanceId: balance._id,
						planId: balance.planId,
					},
				}
			),
		]);
	} catch (err) {
		const error = errorCodes['[0F][初始化用户套餐]保存Mongo记录失败'].from(err);
		log.error({ error, uid }, error.rawMessage);
		throw error;
	}

	this.log.info({ uid }, '初始化用户套餐');
	return balance;
}
